package cn.yuan.xiaoyu.donwloadmodule.activity;

import android.app.DownloadManager;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

import java.util.Timer;
import java.util.TimerTask;

import cn.yuan.xiaoyu.R;
import cn.yuan.xiaoyu.commonmodule.activity.BaseActivity;

/**
 * Created by yukuoyuan on 2017/2/28.
 * 这是一个下载管理的界面
 */
public class DownloadActivity extends BaseActivity {
    /**
     * 文件下载路径
     */
    private String fileurl = "http://7xp26r.com1.z0.glb.clouddn.com/app-debug.apk";
    private TimerTask task;

    @Override
    protected void bindPresenter() {

    }

    @Override
    protected void initData(Bundle extras) {
        /**
         * 获取下载管理
         */
        final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        /**
         * 获取请求
         */
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileurl));
        /**
         * 下载的文件存放的地址,Sd卡,download文件夹
         * 软件卸载后,文件会得到保留
         */
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "xiaoyu.apk");
        /**
         * 指定在wifi状态下执行下载操作
         */
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        /**
         * 设置下载文件类型(这是Android的apk文件类型)
         */
        request.setMimeType("application/vnd.android.package-archive");
        /**
         * 每下载一个文件会得到一个id
         * enqueue(排队,入队的意思)
         */
        final long id = downloadManager.enqueue(request);
        final DownloadManager.Query query = new DownloadManager.Query();
        Timer time = new Timer();
        /**
         * 下载成功之后
         */task = new TimerTask() {
            @Override
            public void run() {
                Cursor cursor = downloadManager.query(query.setFilterById(id));
                if (cursor != null && cursor.moveToFirst()) {
                    /**
                     * 下载成功之后
                     */
                    if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                        install(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/xiaoyu.apk");
                        task.cancel();
                    }
                }
                cursor.close();
            }
        };
        time.schedule(task, 0, 1000);
    }

    /**
     * 安装文件
     *
     * @param path
     */
    private void install(String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_download;
    }

    @Override
    protected void initToolbar() {

    }
}
